using System;
using System.Collections.Generic;
using Logic.Locations;
using Logic.Units;

namespace Logic.MiniGameLogic
{
    public class MiniGame : IMiniGame
    {
        private readonly ICustomRandom _random;
        private List<IUnit> _defenders;
        private List<IUnit> _troops;

        public MiniGame(ICustomRandom random = null)
        {
            _random = random ?? new CustomRandom();
        }

        public void SetOpponents(List<IUnit> defenders, List<IUnit> troops)
        {
            _troops = troops;
            _defenders = defenders;
        }

        public event Action<List<IUnit>> EndGame;

        public void SetWiner(List<IUnit> winer)
        {
            OnEndGame(winer);
        }

        public void Start()
        {
            int i = _random.GetSign() > 0 ? 1 : 0;
            do
            {
                if (_defenders.Count == 0 || _troops.Count == 0) break;

                IUnit d = _defenders[_random.GetRandom(_defenders.Count)];
                IUnit t = _troops[_random.GetRandom(_troops.Count)];

                if (i++%2 == 0)
                {
                    IUnit tmp = d;
                    d = t;
                    t = tmp;
                }

                d.GetDone(t);

                _defenders.RemoveAll(x => x.ActualHp <= 0);
                _troops.RemoveAll(x => x.ActualHp <= 0);
            } while (_defenders.Count > 0 && _troops.Count > 0);

            //return winer.Count > 0 ? winer : troops;
            OnEndGame(_defenders.Count > 0 ? _defenders : _troops);
        }

        protected virtual void OnEndGame(List<IUnit> winer)
        {
            Action<List<IUnit>> handler = EndGame;
            if (handler != null) handler(winer);
        }
    }
}